package cn.walls1717.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * integerFieldUpdater测试
 *
 * @author walls1717
 * @create 2022/12/12 17:15
 **/
@Slf4j
public class AtomicIntegerFieldUpdaterDemo {

    public static void main(String[] args) throws InterruptedException {
        Account account = new Account();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 1; i <= 10; i++) {
            new Thread(()->{
                try {
                    for (int j = 1; j <= 1000; j++) {
                        account.add(account);
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }

        countDownLatch.await();

        log.info("result " + account.money);
    }
}

class Account {
    private String name;
    public volatile int money;

    /**
     * 这个类主要是对类中的某个字段进行原子操作，可以降低锁的粒度，提高性能。
     */
    AtomicIntegerFieldUpdater<Account> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Account.class, "money");

    public void add(Account account) {
        fieldUpdater.getAndIncrement(account);
    }
}
